const query = require('../../db/index');
const jwt = require('jsonwebtoken');
const config = require('../../jwtSecretKey');
// 根据 文章id 获取评论
exports.getComment = async (req, res) => {
    try {
        const { articleId } = req.query;

        if (!articleId) {
            return res.dispatch(400, "Missing articleId parameter");
        }

        const getCommentsSQL = `
            SELECT c.*, u.name, u.avatar
            FROM comments c
            LEFT JOIN user u ON c.id = u.id
            WHERE c.articleId = ?
            ORDER BY c.commentsId ASC
        `;

        const commentResult = await query(getCommentsSQL, [articleId]);

        // Sort comments by commentsId descending (from large to small)
        commentResult.sort((a, b) => b.commentsId - a.commentsId);

        // Organize comments into a tree structure
        const commentsTree = buildCommentsTree(commentResult);

        // Return the structured comments
        return res.dispatch(200, "Success", commentsTree);
    } catch (error) {
        console.error("Error retrieving comments:", error);
        return res.dispatch(500, "Internal Server Error");
    }
}
// 处理评论函数
function buildCommentsTree(comments) {
    // Map to store comments by their commentsId
    const commentsMap = {};
    comments.forEach(comment => {
        comment.children = []; // Initialize children array
        commentsMap[comment.commentsId] = comment;
    });

    // Array to hold root comments (comments without parentId or parentId = 0)
    const commentsTree = [];

    comments.forEach(comment => {
        if (comment.parentId === 0) {
            commentsTree.push(comment); // Add root comments directly to the tree
        } else {
            // Add comments to their parent's children array
            if (commentsMap[comment.parentId]) {
                commentsMap[comment.parentId].children.push(comment);
            } else {
                // Handle case where parent comment doesn't exist (optional)
                console.warn(`Parent comment ${comment.parentId} not found for comment ${comment.commentsId}`);
            }
        }
    });

    return commentsTree;
}
// 添加评论
exports.addComment = async (req, res) => {
    try {
        const { date, content, parentId, level, articleId } = req.body;
        const token = req.headers.authorization; // 假设你的 token 放在请求头的 Authorization 字段中

        // 验证 token
        if (!token) {
            return res.dispatch(401, "Unauthorized: Missing token");
        }

        // 解码 token
        jwt.verify(token.split(' ')[1], config.jwtSecretKey, async (err, decoded) => {
            if (err) {
                console.error("Token verification error:", err);
                return res.dispatch(401, "Unauthorized: Invalid token");
            } else {
                // token 验证成功，可以继续添加评论
                const id = decoded.id; // 从 token 中获取用户 ID

                if (!date || !content || !articleId) {
                    return res.dispatch(400, "Date, content, and articleId are required");
                }

                const addCommentSQL = `
                    INSERT INTO comments (date, content, parentId, level, articleId, id)
                    VALUES (?, ?, ?, ?, ?, ?)
                `;
                const addCommentValues = [date, content, parentId, level, articleId, id];

                const result = await query(addCommentSQL, addCommentValues);

                // 返回添加评论成功的响应
                return res.dispatch(200, "Comment added successfully", { commentId: result.insertId });
            }
        });

    } catch (error) {
        console.error("Error adding comment:", error);
        return res.dispatch(500, "Internal Server Error");
    }
}
